﻿<div id="chat" style="margin-top:50px; width:350px;">
    <div id="divStartChat">
        <button type="button" class="btn" id="startChat" style="display:inline-block;">
            <img src="~/Images/User-Chat-icon-24.png" height="24" width="24"> Start Chat
        </button>
    </div>
    <div style="margin-top:10px;">
        <label id="selectContactToChat"><b>Select a contact to chat:</b></label>
        <ul id="contacts"></ul>
    </div>
    <div id="divTextChat">
        <div style="width: 70%; float:left; max-width: 230px;"> 
            <input type="text" id="message" style="max-width: 230px; margin-top: 0px; height: 23px;" />
            <input type="hidden" id="displayname" style="max-width: 230px;"/>
            <div id="discussionBox" style="width: 340px; height: auto; border-style:solid; border-color: rgb(182, 180, 180); border-width: 1px; border-radius: 4px;">
                <ul id="discussion" style="max-width: 230px;list-style-type: none;margin: 5px 0 5px 5px;">
                </ul>
            </div>
        </div>
        <div style="height:30px; float:right;">             
            <button type="button" class="btn btn-primary" id="sendmessage" style="display:inline-block;">Send <img src="~/Images/navigate-right-icon-24.png" height="24" width="24"></button>
        </div>      
    </div>
    <input id="hdId" type="hidden" />
    <input id="chatingWithId" type="hidden" />
</div>

@section scripts {
    <script src="~/Scripts/jquery.signalR-1.1.2.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>

    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.  
            var chat = $.connection.chatHub;

            registerClientMethods(chat);

            // Start the connection.
            $.connection.hub.start().done(function () {
                registerEvents(chat);
            });

        });

        function registerEvents(chat) {

            $("#startChat").click(function () {
                chat.server.connect($('#spanUserName')[0].textContent);                
            });

            $('#sendmessage').click(function () {

                // Call the Send method on the hub. 
                chat.server.sendPrivateMessage($('#chatingWithId').val(), $('#message').val());
                $('#message').val('').focus();
            });

        }

        function registerClientMethods(chat) {

            // Cuando me conecto agrego a todos los usuarios logeados.
            chat.client.onConnected = function (id, userName, allUsers) {
                $('#hdId').val(id);

                // Add All Users
                for (i = 0; i < allUsers.length; i++) {
                    AddUserToList(chat, allUsers[i].ConnectionId, allUsers[i].UserName);
                }
            };

            // Cuando alguien se conecta lo agrego a la lista de usuarios.
            chat.client.onNewUserConnected = function (id, name) {
                if ($('#hdId').val() != "") {
                    AddUserToList(chat, id, name);
                }
            }

            chat.client.sendPrivateMessage = function (toUserId, fromUserId, fromUserName, message) {
                var userId = $('#hdId').val();
                var chatingWithId = "";
                if (userId == toUserId) {
                    chatingWithId = fromUserId;
                } else {
                    chatingWithId = toUserId;
                }

                $("#contacts").children().css('color', 'black');
                $('#li' + chatingWithId).css('color', 'red');

                if (chatingWithId != $('#chatingWithId').val()) {
                    CreateNewChat(chat, fromUserId, fromUserName);
                }

                AddMessageToChat(fromUserName, message);
            }

            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (userId, userName, usrMessage) {
                AddMessageToChat(userName, usrMessage);
            };

            // On User Disconnected
            chat.client.onUserDisconnected = function (id, userName) {

                $('#li' + id).remove();

                if (chatingWithId != $('#chatingWithId').val()) {
                    alert(userName + ' ha abandonado el chat.');
                }
            }

        }

        function AddMessageToChat(userName, usrMessage) {
            // Add the message to the page.
            $('#discussionBox').show();
            $('#discussion').append('<li><strong>' + htmlEncode(userName) + '</strong>: ' + htmlEncode(usrMessage) + '</li>');
        }

        function AddUserToList(chat, newUserId, newUserName) {
            var userId = $('#hdId').val();
           
            var code = "";
            code = $('<li id="li' + newUserId + '"><strong>' + htmlEncode(newUserName) + '</strong></li>');
            
            if (userId != newUserId) {
                $(code).click(function () {
                    if (newUserId != $('#chatingWithId').val()) {
                        CreateNewChat(chat, newUserId, newUserName);
                    }
                    $('#message').focus();
                });
            }

            $("#selectContactToChat").show();
            $("#contacts").append(code);
        }

        function CreateNewChat(chat, newUserId, newUserName) {
            $('#discussion').children().remove();
            $('#chatingWithId').val(newUserId);
        }

        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }

        $(document).ready(function () {
            $("#selectContactToChat").hide();
            $("#discussionBox").hide();
        });

    </script>
}